package com.ems.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ems.entity.CameraEntity;
import com.ems.mapper.CameraMapper;
import com.ems.service.ICameraService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ems.util.SnowflakeIdWorker;
import com.ems.util.StateEnum;
import com.ems.util.StateException;
import com.ems.vo.CameraVo;
import com.fasterxml.jackson.databind.util.BeanUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>
 * 摄像头 服务实现类
 * </p>
 * @author WuZH
 * @since 2023-11-08
 */
@Service
public class CameraServiceImpl extends ServiceImpl<CameraMapper, CameraEntity> implements ICameraService {

    @Resource
    private CameraMapper cameraMapper;
    //存放摄像头每个通道的推流进程信息
    public static Map<String, Process> processMap = new ConcurrentHashMap<> ();

    @Override
    public List<CameraVo> queryList (CameraVo cameraVo) {
        cameraVo.setPage ( ( cameraVo.getPage () - 1 ) * cameraVo.getLimit () );
        List<CameraVo> cameraVos = cameraMapper.queryList ( cameraVo );
        return cameraVos;
    }

    @Override
    public Integer queryCount (CameraVo cameraVo) {
        Integer count = cameraMapper.queryCount ( cameraVo );
        return count;
    }

    @Override
    public CameraVo saveSingle (CameraVo cameraVo) {
        if ( cameraVo == null ) {
            throw new StateException ( StateEnum.REQUEST_PARAM_EXCE );
        }
        CameraEntity cameraEntity = new CameraEntity ();
        BeanUtils.copyProperties ( cameraVo, cameraEntity );
        cameraEntity.setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
        int insert = baseMapper.insert ( cameraEntity );
        if ( insert == 0 ) {
            throw new StateException ( StateEnum.INSERT_EXCE );
        }
        return cameraVo;
    }

    @Override
    public CameraVo querySingle (CameraVo cameraVo) {
        QueryWrapper<CameraEntity> queryWrapper = new QueryWrapper<> ();
        if ( StringUtils.isNotBlank ( cameraVo.getId () ) ) {
            queryWrapper.eq ( "id", cameraVo.getId () );
        }
        CameraEntity cameraEntity = baseMapper.selectOne ( queryWrapper );
        BeanUtils.copyProperties ( cameraEntity, cameraVo );
        return cameraVo;
    }

    @Override
    public void kill (String cameraCode) {
        try {
            for ( String key : processMap.keySet () ) {
                if ( key.contains ( cameraCode ) ) {
                    processMap.get ( key ).destroy ();
                }
            }
        } catch ( NullPointerException e ) {
            e.printStackTrace ();
        }
    }

}
